package com.easemob.chatuidemo.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by dllo on 15/8/31.
 */
public class CircleImageView extends ImageView {
    private Matrix matrix;
    private Paint paint;// 绘图的paint
    private int width;
    private int radius;
    private BitmapShader bitmapShader;


    public CircleImageView(Context context) {
        super(context);
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        matrix = new Matrix();
        paint = new Paint();
        paint.setAntiAlias(true);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        width = Math.min(getMeasuredWidth(), getMeasuredHeight());// 圆形宽高一致,以小值为准
        radius = width / 2;// 圆形半径
        setMeasuredDimension(width,width); // imageView 的宽高
    }



    private void setUpShader() {
        Drawable drawable = getDrawable();
        if (drawable == null) {
            return;
        }

        Bitmap bitmap = drawableToBitmap(drawable);
        bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        float scale = 1.0f;
        int bSize = Math.min(bitmap.getWidth(), bitmap.getHeight());// 拿到bitmap宽或高的小值
        scale = width * 1.0f / bSize;
        // shader的变换矩阵,用于放大或缩小
        matrix.setScale(scale, scale);
        // 设置变换矩阵
        bitmapShader.setLocalMatrix(matrix);
        // 设置shader
        paint.setShader(bitmapShader);

    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;

            return bitmapDrawable.getBitmap();
        }

        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);

        drawable.setBounds(0,0,w,h);
        drawable.draw(canvas);
        return bitmap;

    }


    @Override
    protected void onDraw(Canvas canvas) {

        setScaleType(ScaleType.FIT_END);// 把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置

        if (getDrawable() == null) {
            return;
        }

        setUpShader();

        canvas.drawCircle(radius,radius,radius,paint);

    }

}